#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import TypeVar

from sqlalchemy import or_
from sqlalchemy.orm import Session

from app.models import User
from pydantic import BaseModel

from app.dao.base_dao import BaseDao
from app.db.base_class import Base
from app.models.bar import Bar
from app.models.constant import Constant
from app.models.instrument import Instrument
from app.models.strategy import Strategy
from app.models.user_setting import UserSetting
from app.schemas.instrument import PickableQuery


class InstrumentDao(BaseDao[Instrument]):
    def __init__(self):
        super(InstrumentDao, self).__init__()
        self.modelClass = Instrument
        self.id = Instrument.id

    def selectByKeywords(self, db: Session, keywords: str):
        result = db.query(Instrument).filter(or_(Instrument.symbol.like(keywords + '%'),
                                                 Instrument.name.like(keywords + '%'),
                                                 Instrument.nameLetter.like(keywords + '%'))
                                             ).limit(20).all()
        return result

    def selectPickableInstruments(self, db: Session, queryWrapper: PickableQuery):
        filters = {
            Instrument.id == Bar.instrumentId,
            Instrument.exchangeId == queryWrapper.exchangeId,
            Bar.barDate == queryWrapper.barDate,
            Bar.frequency == queryWrapper.frequency
        }
        if queryWrapper.isSt is not None:
            filters.add(Bar.isSt == queryWrapper.isSt)
        if queryWrapper.tradeStatus is not None:
            filters.add(Bar.tradeStatus == queryWrapper.tradeStatus)
        instruments = db.query(Instrument.id).filter(*filters).all()
        return instruments


instrumentDao = InstrumentDao()
